<template>
  <v-layout :title="$route.query.id?'修改买量记录':'添加买量记录'">
    <el-row type="flex" justify="center" class="confirm">
      <el-col :xl="14" :lg="18" :md="20" :sm="24" :xs="24">
        <v-form
          :form-title="formTitle1"
          :form-data="formData1"
          label-width="100px"
          @focus="focus"
        />

        <record-table
          :table-title="paymentTitle"
          :table-data="paymentData"
          title="付款记录"
          @addNew="addPayment"
          @edit="editPayment"
          @del="delPayment"
        />

        <v-form
          :form-title="formTitle2"
          :form-data="formData"
          class="mt15"
          label-width="100px"
        />

        <record-table
          :table-title="verifyTitle"
          :table-data="verifyData"
          title="核销记录"
          @addNew="addVerify"
          @edit="editVerify"
          @del="delVerify"
        />

        <record-table
          :table-title="invoiceTitle"
          :table-data="invoiceData"
          title="发票信息"
          @addNew="addInvoice"
          @edit="editInvoice"
          @del="delInvoice"
        />

        <el-form label-width="120px" size="mini" class="mt15 confirm">
          <el-form-item label="发票总金额">
            <el-input v-model="totalMoney" :disabled="true"/>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="formData.notes" type="textarea"/>
          </el-form-item>
        </el-form>

        <div v-if="messages.length">
          <div class="pdv15 bold">
            合同审批记录
          </div>
          <v-messageBox
            :messages="messages"
          />
        </div>

        <el-row type="flex" justify="end" class="pdt15">
          <el-button type="primary" size="small" @click="reset">撤销修改</el-button>
          <el-button type="primary" size="small" @click="submit">确定</el-button>
        </el-row>
      </el-col>
    </el-row>

    <!--选择合同-->
    <el-dialog
      :visible.sync="showContractDialog"
      width="60%"
      title="请选择合同"
    >
      <contract
        @use="useContract"
      />
    </el-dialog>

    <!--创建付款银行-->
    <el-dialog
      :visible.sync="showDialog"
      :title="dialogTitle"
      width="30%"
    >
      <v-form
        :form-title="modifyTitle"
        :form-data="modifyData"
        label-width="120px"
        @change="changeTencent"
      />
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="cancelModify">取 消</el-button>
        <el-button size="mini" type="primary" @click="modified">确 定</el-button>
      </span>
    </el-dialog>

  </v-layout>
</template>

<script>
  import contract from '../components/contractSelect'
  import recordTable from '../../components/record_table'
  import uploadFile from '@/views/components/uploadFiles'

  export default {
    components: { contract, uploadFile, recordTable },
    data() {
      return {
        buy_fans_record_id: '',
        dialogTitle: '',
        showModel: false,
        showDialog: false,
        showContractDialog: false,
        previewUrl: '',
        fileList: [],

        formTitle1: [
          {
            cn: '合同编号',
            en: 'ct_number',
            focus: true
          },
          {
            cn: '合同附件',
            en: 'appendices',
            disabled: true
          },
          {
            cn: '对方单位名称',
            en: 'opposing_party_unit',
            disabled: true
          },
          {
            cn: '对方联系人',
            en: 'contact_person',
            disabled: true
          },
          {
            cn: '采购内容',
            en: 'procurement_contents',
            type: 'textarea',
            disabled: true
          },
          {
            cn: '合同金额',
            en: 'money'
            // disabled: true
          },
          {
            cn: '税点',
            en: 'tax_point'
          },
          {
            cn: '已付款金额',
            en: 'real_pay',
            disabled: true
          },
          {
            cn: '付款状态',
            en: 'payment_status',
            type: 'select',
            disabled: true,
            list: [
              {
                label: '未收款',
                value: '1'
              },
              {
                label: '部分收款',
                value: '2'
              },
              {
                label: '已完成',
                value: 'COMPLETED'
              }
            ]
          }
        ],

        formTitle2: [
          {
            cn: '签订日期',
            en: 'date_of_signing',
            disabled: true
          },
          {
            cn: '合同状态',
            en: 'contract_status',
            type: 'select',
            disabled: true,
            list: [
              {
                label: '签约',
                value: '1'
              },
              {
                label: '执行中',
                value: '2'
              },
              {
                label: '完毕',
                value: '3'
              },
              {
                label: '意外终止',
                value: '4'
              }
            ]
          },
          {
            cn: '签订人',
            en: 'signing_people',
            disabled: true
          },
          {
            cn: '核销总金额',
            en: 'verifyMoney',
            disabled: true
          }
        ],
        formData: {},

        // 打款
        paymentTitle: [
          {
            cn: '付款银行',
            en: 'bank'
          },
          {
            cn: '付款金额',
            en: 'money'
          },
          {
            cn: '付款时间',
            en: 'create_date'
          }
          // {
          //   cn: '修改人',
          //   en: 'name'
          // },
          // {
          //   cn: '最后提交时间',
          //   en: 'update_date'
          // }
        ],
        paymentData: [],
        paymentFormTitle: [
          {
            cn: '付款银行',
            en: 'bank'
          },
          {
            cn: '付款金额',
            en: 'money'
          },
          {
            cn: '付款时间',
            en: 'create_date',
            type: 'time'
          }
        ],

        // 核销记录
        verifyTitle: [
          {
            cn: 'id',
            en: 'id'
          },
          {
            cn: '核销公众号',
            en: 'mpsname'
          },
          {
            cn: '核销金额',
            en: 'money'
          },
          {
            cn: '不含税原值',
            en: 'balance'
          },
          {
            cn: '核销时间',
            en: 'start_time'
          },
          {
            cn: '周期',
            en: 'cycle'
          },
          {
            cn: '每月摊销',
            en: 'per_month_cost'
          }
        ],
        verifyData: [],
        verifyFormTitle: [
          {
            cn: '核销公众号',
            en: 'mpsid',
            type: 'select',
            list: []
          },
          {
            cn: '核销金额',
            en: 'money'
          },
          {
            cn: '核销时间',
            en: 'start_time',
            type: 'time'
          }
        ],

        // 发票信息
        invoiceTitle: [
          {
            cn: '开票号码',
            en: 'invoice_code'
          },
          {
            cn: '对方公司',
            en: 'company'
          },
          {
            cn: '含税金额',
            en: 'money'
          },
          {
            cn: '开票时间',
            en: 'create_date'
          }
          // {
          //   cn: '修改人',
          //   en: 'name'
          // }
        ],
        invoiceData: [],
        invoiceFormTitle: [
          {
            cn: '开票号码',
            en: 'invoice_code'
          },
          {
            cn: '对方公司',
            en: 'company'
          },
          {
            cn: '含税金额',
            en: 'money'
          },
          {
            cn: '开票时间',
            en: 'create_date',
            type: 'time'
          }
        ],

        messages: [],

        tencentList: [],

        modifyTitle: [],
        modifyData: {},
        submitUrl: '',
        current: false,

        currentModified: '',

        isEdit: false,   //是否是修改表格
        index: null    // 是修改时的序号
      }
    },
    computed: {
      totalMoney() {
        let total = 0
        this.invoiceData.forEach(item => {
          total += +(item.money || 0)
        })
        return total
      },
      formData1() {
        const obj = this.formData
        let money = 0
        this.verifyData.forEach(item => {
          money += (+item.money || 0)
        })
        obj.verifyMoney = money
        return obj
      },
      orderWarning() {
        return !this.formData.ct_number
      },
      payedMoney() {
        let total = 0
        this.paymentData.forEach(item => {
          total += +(item.money || 0)
        })
        if (!total) {
          this.formData.real_pay = total
        }
        return total
      }
    },
    watch: {
      tencentList(val) {
        this.verifyFormTitle[0].list = val
      },
      payedMoney(val) {
        this.$set(this.formData, 'real_pay', val)
      }
    },
    activated() {
      localStorage.removeItem('paymentData')
      localStorage.removeItem('invoiceData')
      localStorage.removeItem('verifyData')

      this.buy_fans_record_id = this.$route.query.id
      if (this.buy_fans_record_id) {
        this.getBuyQuantityDetail()
      } else {
        this.formData = {}
        this.paymentData = []
        this.verifyData = []
        this.invoiceData = []
      }
    },
    mounted() {
      this.getTencentList()
    },
    methods: {
      // 获取买量记录详情
      getBuyQuantityDetail() {
        const data = { id: this.buy_fans_record_id }
        this.$get('action/BuyfansRecord/qryOp', data)
          .then(res => {
            this.verifyData = res.data.Buyfansmpinfo.map(item => {
              item.per_month_cost = (item.balance / 60).toFixed(2)
              return item
            }) || []// 买量核销记录
            // this.formData = res.data.BuyfansRecord|| {}// 买量合同
            this.formData = { ...res.data.BuyfansRecord, ...this.formData } || {}// 买量合同
            this.invoiceData = res.data.Buyfansinvoiceinfo || []// 买量票信息
            this.paymentData = res.data.Buyfanspayrecord || []// 买量打款
          })
      },

      // 选用该条合同详情
      useContract(val) {
        this.formData = val.row
        this.showContractDialog = false
      },

      focus(val, name) {
        console.log(val)
        this.showContractDialog = true
      },

      editPayment(val) {
        this.dialogTitle = '修改付款记录'
        this.handelModify(this.paymentFormTitle, val.row)
        this.submitUrl = 'action/Buyfanspayrecord/save'
        this.key = 'paymentData'
        this.isEdit = true
        this.index = val.$index
      },
      addPayment() {
        this.dialogTitle = '添加付款记录'
        this.handelModify(this.paymentFormTitle)
        this.submitUrl = 'action/Buyfanspayrecord/save'
        this.key = 'paymentData'
      },
      delPayment(val) {
        if (this.buy_fans_record_id) {
          const data = {
            id: val.row.id,
            buy_fans_record_id: this.buy_fans_record_id
          }
          this.$post('action/Buyfanspayrecord/del', data)
            .then(res => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.getBuyQuantityDetail()
            })
        } else {
          this.paymentData.splice(val.$index, 1)
        }

      },
      editVerify(val) {
        this.dialogTitle = '修改核销记录'
        this.handelModify(this.verifyFormTitle, val.row)
        this.submitUrl = 'action/Buyfansmpinfo/save'
        this.key = 'verifyData'
        this.isEdit = true
        this.index = val.$index
      },
      addVerify() {
        this.dialogTitle = '添加核销记录'
        this.handelModify(this.verifyFormTitle)
        this.submitUrl = 'action/Buyfansmpinfo/save'
        this.key = 'verifyData'
      },

      delVerify(val) {
        if (this.buy_fans_record_id) {
          const data = {
            id: val.row.id,
            buy_fans_record_id: this.buy_fans_record_id
          }
          this.$post('action/Buyfansmpinfo/del', data)
            .then(res => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.getBuyQuantityDetail()
            })
        } else {
          this.verifyData.splice(val.$index, 1)
        }
      },

      // 添加/删除发票信息
      addInvoice() {
        this.dialogTitle = '添加发票信息'
        this.handelModify(this.invoiceFormTitle)
        this.submitUrl = 'action/Buyfansinvoiceinfo/save'
        this.key = 'invoiceData'
      },
      editInvoice(val) {
        this.dialogTitle = '修改发票信息'
        this.handelModify(this.invoiceFormTitle, val.row)
        this.submitUrl = 'action/Buyfansinvoiceinfo/save'
        this.key = 'invoiceData'
        this.isEdit = true
        this.index = val.$index
      },
      delInvoice(val) {
        if (this.buy_fans_record_id) {
          const data = {
            id: val.row.id,
            buy_fans_record_id: this.buy_fans_record_id
          }
          this.$post('action/Buyfanspayrecord/del', data)
            .then(res => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.getBuyQuantityDetail()
            })
        } else {
          this.invoiceData.splice(val.$index, 1)
        }
      },

      handelModify(title, val) {
        this.modifyData = val && this.$deepClone(val) || {}
        this.modifyData.tax_point = this.formData.tax_point || 0
        this.modifyTitle = title
        this.showDialog = true
        this.current = false
      },

      cancelModify() {
        this.modifyTitle = null
        this.showDialog = false
        this.modifyData = {}
      },
      modified() {
        // this.modifyData.id = this.modifyData.id ? '' + this.modifyData.id : ''
        const status = this.modifyTitle.every(item=>{
          return this.modifyData[item.en]||this.modifyData[item.en]==0
        })
        if (!status) {
            return this.$message({
              message: '请填写完整',
              type: 'error'
            })
          }
        if (this.key === 'verifyData') {

          const money = this.modifyData.money
          const point = this.modifyData.tax_point || 0
          this.modifyData.balance = (money / (1 + point)).toFixed(2)
          this.modifyData.per_month_cost = (this.modifyData.balance / 60).toFixed(2)
          this.modifyData.cycle = 60
        }
        const data = {
          buy_fans_record_id: this.buy_fans_record_id,
          ...this.modifyData
        }
        if (this.buy_fans_record_id) {
          this.$post(this.submitUrl, data)
            .then(res => {
              this.modifyTitle = null
              this.modifyData = {}
              this.submitUrl = ''
              this.getBuyQuantityDetail()
            })
        } else {
          let lists = localStorage.getItem(this.key) ? JSON.parse(localStorage.getItem(this.key)) : []
          if (this.isEdit) {  //如果是修改
            this.$set(this[this.key], this.index, data)
          } else { // 如果是新增
            lists.push(data)
            this[this.key].push(data)
          }
          localStorage.setItem(this.key, JSON.stringify(lists))
          this.isEdit = false
          this.index = null
        }
        this.showDialog = false
      },

      // 公众号改变
      changeTencent(val) {
        console.log(val)
        this.tencentList.forEach(item => {
          if (item.value === val) {
            this.modifyData.mpsname = item.label
            this.modifyData.mpsid = val
          }
        })
        this.current = true
      },

      // 获取公众号列表
      getTencentList() {
        this.$get('action/WechatNumber/tree')
          .then(res => {
            const list = []
            if (res.data.WechatTree) {
              res.data.WechatTree.forEach(item => {
                list.push({
                  label: item.name,
                  value: item.id
                })
              })
            }
            this.tencentList = list
          })
      },

      reset() {
        this.getBuyQuantityDetail()
      },

      // 获取买量记录id
      getQuantityRecordId() {
        return new Promise((resolve, reject) => {
          this.$get('action/BuyfansRecord/save')
            .then(res => {
              this.buy_fans_record_id = res.data
              resolve(res)
            })
            .catch(err => {
              reject(err)
            })
        })
      },

      submitTable(url, data) {
        if (data && data instanceof Array && data.length > 0) {
          data.forEach(item => {
            item.buy_fans_record_id = this.buy_fans_record_id
            item.tax_point = this.formData.tax_point || 0
            this.$post(url, item)
              .then(res => {

              })
          })
        }
      },

      submit() {
        if (this.orderWarning) {
          this.$alert('请选择合同', '提示', {
            confirmButtonText: '确定'
          })
        } else {
          if (this.buy_fans_record_id) {
            this.submit2()
          } else {
            this.getQuantityRecordId()
              .then(res => {
                const data1 = localStorage.getItem('paymentData') ? JSON.parse(localStorage.getItem('paymentData')) : []
                const data2 = localStorage.getItem('invoiceData') ? JSON.parse(localStorage.getItem('invoiceData')) : []
                const data3 = localStorage.getItem('verifyData') ? JSON.parse(localStorage.getItem('verifyData')) : []
                this.submitTable('action/Buyfanspayrecord/save', data1)
                this.submitTable('action/Buyfansinvoiceinfo/save', data2)
                this.submitTable('action/Buyfansmpinfo/save', data3)
                this.submit2()
              })

          }
        }
      },
      submit2() {
        const data = {
          id: +this.buy_fans_record_id,
          ...this.formData,
          money: this.formData.money || 0,
          tax_point: this.formData.tax_point || 0
        }
        this.$post('action/BuyfansRecord/update', data)
          .then(res => {
            new Promise((resolve, reject) => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              resolve()
            }).then(_ => this.$router.go(-1))
          })
      }

    }

  }
</script>

